import TioHandler from './TioHandler';

/* eslint-disable no-unused-expressions */
export default class TioWs {
  wsUrl: string | URL = '';

  protocols: string | string[] = [];

  handler: any = {};

  heartbeatTimeout = 5 * 1000;

  reconnInterval = 3 * 1000;

  binaryType: 'arraybuffer' | 'blob' = 'arraybuffer';

  constructor(
    wsUrl: string | URL,
    handler?: TioHandler, // 回调函数
    protocols?: string | string[],
    heartbeatTimeout?: number,
    reconnInterval?: number,
    binaryType?: 'arraybuffer' | 'blob',
  ) {
    this.wsUrl = wsUrl;
    this.protocols = protocols ?? this.protocols;
    this.handler = handler ?? new TioHandler();
    this.heartbeatTimeout = heartbeatTimeout ?? this.heartbeatTimeout;
    this.reconnInterval = reconnInterval ?? this.reconnInterval;
    this.binaryType = binaryType ?? this.binaryType;

    this.init();
  }

  ws: WebSocket | null = null;

  pingIntervalId: any = null;

  init() {
    this.ws = new WebSocket(this.wsUrl, this.protocols);
    this.ws.binaryType = this.binaryType;

    this.ws.onopen = (event) => {
      // eslint-disable-next-line no-console
      console.log('[TioWs] onopen:', event);

      this.pingIntervalId = setInterval(() => {
        this.ping();
      }, this.heartbeatTimeout);
    };

    this.ws.onmessage = (event) => {
      this.handler.onmessage(event);
    };

    this.ws.onclose = () => {
      this.close();
    };
  }

  close() {
    if (this.ws) {
      this.ws.close();
      this.pingIntervalId && clearInterval(this.pingIntervalId);
    }
  }

  ping() {
    if (this.ws) {
      this.ws.send('ping');
    }
  }
}
